package com.atguigu.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hfh
 * @version 1.0
 * @date 2022/8/15 15:26
 */
public class PhoenixUtil {
    /**
     * 用于执行phoenix建表语句
     * @param sql
     * @param conn
     */
    public static void executeSql(String sql, Connection conn){
        PreparedStatement preparedStatement=null;
        try{
            //获取数据库操作对象
            preparedStatement = conn.prepareStatement(sql);
            //执行SQL语句
            preparedStatement.execute();
        }catch (SQLException e){
            e.printStackTrace();
            System.out.println("Phoenix建表异常");
        }finally {
            close(preparedStatement,conn);
        }
    }

    /**
     * 用于释放资源
     * @param preparedStatement
     * @param conn
     */
    private static void close(PreparedStatement preparedStatement, Connection conn) {
        if (preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

//select * from t where k=v and k1=v1
    public  static <T>List<T> sqlQuery(Connection connection,String sql,Class<T> clz) {
        ArrayList<T> result = new ArrayList<>();

        //给泛型的对象添加属性
        PreparedStatement ps = null;

       try{
           ps = connection.prepareStatement(sql);
           ResultSet rs = ps.executeQuery();

           //获取一行数据
           while (rs.next()) {
               //new 一个javabean
               T t = clz.newInstance();
               //获取对应的元数据  即列名
               ResultSetMetaData metaData = rs.getMetaData();
               for (int i = 1; i <= metaData.getColumnCount(); i++) {
                   String columnName = metaData.getColumnName(i);
                   String value = rs.getString(i);
                   String colName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                   BeanUtils.setProperty(t, colName, value);

               }
               result.add(t);
           }
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("PhoenixUtil：读取维度表数据异常！");
       }
       finally {
           close(ps,connection);
       }

        return result;
    }
 }

